#include "mb.h"
#include "mbport.h"
#include "tcpserver.h"

//#define PKG_MODBUS_DEBUG

#define DBG_TAG    "modbus"
#ifdef  PKG_MODBUS_DEBUG
#define DBG_LVL    DBG_LOG
#else
#define DBG_LVL    DBG_INFO
#endif
#include <rtdbg.h>

#define MB_TCP_DEFAULT_PORT 502 /* TCP listening port. */

struct tcpserver* modbustcp;
static UCHAR ucTCPRequestFrame[1024];
static USHORT ucTCPRequestLen;
tcpclient_t modbuscli;//�����ӵĿͻ���

void modbustcpNotify(tcpclient_t client, rt_uint8_t event);

BOOL xMBTCPPortInit( USHORT usTCPPort )
{
    BOOL bOkay = FALSE;

    USHORT usPort;
    if( usTCPPort == 0 )
    {
        usPort = MB_TCP_DEFAULT_PORT;
    }
    else
    {
        usPort = (USHORT)usTCPPort;
    }

    // �����˿� 502�˿�
    modbustcp = tcpserver_create(RT_LWIP_IPADDR,usPort);
    tcpserver_set_notify_callback(modbustcp,modbustcpNotify);

    bOkay = TRUE;
    return bOkay;
}

void modbustcpNotify(tcpclient_t client, rt_uint8_t event)
{
    int ret;
    switch (event) {
        case TCPSERVER_EVENT_CONNECT:
            LOG_D("modbus connect:%d", client->sock);
            break;
        case TCPSERVER_EVENT_DISCONNECT:
            LOG_D("modbus disconnect:%d", client->sock);
            break;
        case TCPSERVER_EVENT_RECV:
            ret = tcpserver_recv(client, ucTCPRequestFrame, 1024, -1);
            if (ret > 0)
            {
                LOG_D("request!\r\n");
                modbuscli = client;
                // ���modbus����
                ucTCPRequestLen = ret;
                // �� modbus poll������Ϣ
                xMBPortEventPost( EV_FRAME_RECEIVED );
            }
            break;
        default:
            LOG_E("unknown failed!");
            break;
    }
}

BOOL xMBTCPPortGetRequest( UCHAR ** ppucMBTCPFrame, USHORT * usTCPLength )
{
    *ppucMBTCPFrame = &ucTCPRequestFrame[0];
    *usTCPLength = ucTCPRequestLen;

    /* Reset the buffer. */
    ucTCPRequestLen = 0;
    return TRUE;
}

void vMBTCPPortDisable( void )
{
    tcpserver_destroy(modbustcp);
}

BOOL xMBTCPPortSendResponse( const UCHAR * pucMBTCPFrame, USHORT usTCPLength )
{
    tcpserver_send(modbuscli, (void *)pucMBTCPFrame, usTCPLength, 0);
    return TRUE;
}
